/**
 * 
 */
var xmlhttp;
var callBackObj;
var page=1;
var searchInfo="";
function initAjax() {//初始化ajax
	if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else{// code for IE6, IE5
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
}
function callback(){
    //alert(xmlHttp.readyState);  
    //Ajax引擎状态为成功  
    if (xmlhttp.readyState == 4) {
        //HTTP协议状态为成功  
        if (xmlhttp.status == 200) {
        	switch (callBackObj) {
			case "homeSearch":
				if (xmlhttp.responseText ==-1) {
                	setCookie("pageTotal", 0);
                }else if(xmlhttp.responseText >=0){
                	setCookie("pageTotal",xmlhttp.responseText);
                	window.location.href="pages/search.jsp";
                }else { 
                	alert("无法连接服务器");
                } 
				break;
			case "search":
				if (xmlhttp.responseText ==-1) {
					setCookie("pageTotal", 0);
                }else if(xmlhttp.responseText >=0){
                	setCookie("pageTotal",xmlhttp.responseText);
                	window.location.href="search.jsp";
                }else { 
                	alert("无法连接服务器");
                } 
				break;
			case "pageSearch":
				if (xmlhttp.responseText == "false") {	
                }else if(xmlhttp.responseText =="true"){
                	window.location.href="search.jsp?page="+page;
                }else { 
                	alert("无法连接服务器");
                }
				break;
			case "orderBookUpdate":
				var books=eval(xmlhttp.responseText);
				var table=document.getElementById("books");
				var tableLength=table.rows.length;
				var totaPrice=0.0;
				for(var i=1;i<tableLength-1;i++){
					if(table.rows[i].cells[0].getElementsByTagName("input")[0].checked){
						totaPrice+=(parseFloat(books[i-1].amount)*parseFloat(books[i-1].item.unprice));
					}
					table.rows[i].cells[4].innerHTML=(parseFloat(books[i-1].amount)*parseFloat(books[i-1].item.unprice)).toFixed(1);
				}
				table.rows[tableLength-1].cells[4].innerHTML="￥"+totaPrice.toFixed(1);
				break;
			default:
				break;
			}
        }else { 
            alert("请求失败，错误码=" + xmlhttp.status); 
        } 
    } 
}
//搜索图书
function search() {
	var searchInfo=document.getElementById("txt-search").value;
	if(document.title=="HOME"){
		callBackObj="homeSearch";
		if(searchInfo!=""){
			page=0;
			initAjax();
			setCookie("search", searchInfo);
			setCookie("BookType",0);
			setCookie("type", "name");
			var url="BookServlet?opt=search";
			var data="btype=title&page=0&pageCount=12&sort=desc&sorttype=id&fuzzy=true&name="+searchInfo;
			url=urlDeal(url);
			xmlhttp.open("post",url,true);
			xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			xmlhttp.onreadystatechange = callback;
			xmlhttp.send(urlDeal(data));
			}
	}else{
		callBackObj="search";
		page=0;
		if(searchInfo!=""){
			doSearch("","name");
		}
	}
}
function CategorySearch(fuzzy) {
	page=0;
	callBackObj="search";
	doSearch(fuzzy,"category");
}
function publisherSearch(fuzzy){
	page=0;
	callBackObj="search";
	doSearch(fuzzy,"publisher");
}
function doSearch(fuzzy,type){
	initAjax();
	var data;
	switch (type) {
	case "category":
		//按种类查找
		setCookie("search", "");
		setCookie("BookType",fuzzy);
		setCookie("type", "category");
		var url="../BookServlet?opt=search";
		data="btype=categoryId&page="+page+"&pageCount=12&sort=desc&sorttype=id&fuzzy=false&name="+fuzzy;
		xmlhttp.open("post",url,true);
		break;
	case "name":
		//按图书名查找
		searchInfo=document.getElementById("txt-search").value;
		setCookie("search", searchInfo);
		setCookie("BookType",0);
		setCookie("type", "name");
		var url="../BookServlet?opt=search";
		data="btype=title&page="+page+"&pageCount=12&sort=desc&sorttype=id&fuzzy=true&name="+searchInfo;
		url=urlDeal(url);
		xmlhttp.open("post",url,true);
		break;
	case "publisher":
		//出版社查找
		searchInfo=document.getElementById("txt-search").value;
		setCookie("search", "");
		setCookie("BookType",fuzzy);
		setCookie("type", "publisher");
		var url="../BookServlet?opt=search";
		data="btype=publisherId&page="+page+"&pageCount=12&sort=desc&sorttype=id&fuzzy=false&name="+fuzzy;
		url=urlDeal(url);
		xmlhttp.open("post",url,true);
		break;
	default:
		break;
	}
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = callback;
	xmlhttp.send(urlDeal(data));
}
//购物车数量加减按钮功能
function bookNumChange(id, type) {
	var num
	if(id=="this"){
		num=parseInt(document.getElementById("bookNum").value);
	}else{
		var check_id=document.getElementById("check_"+id);
		if(!check_id.checked){
			check_id.checked=true;
		}
		num=parseInt(document.getElementById("booknum_"+id).value);
	}
	switch (type) {
	case "add":
		num++;
		break;
	case "reduce":
		if(num>1){
			num--;
		}
		break;
	default:
		break;
	}
	if(id=="this"){
		document.getElementById("bookNum").value=num;
	}else{
		document.getElementById("booknum_"+id).value=num;
		initAjax();
		var url="../ShoppingCartServlet?method=update&num="+num+"&bookId="+id;
		callBackObj="orderBookUpdate";
		xmlhttp.open("post",url,true);
		xmlhttp.onreadystatechange = callback;
		xmlhttp.send(null);
	}
}
//加入购物车按钮
function addShopping(bookId,isOne) {
	var bookNum=1;
	if(isOne!="true"){
		bookNum=document.getElementById("bookNum").value;
	}
	window.open("../ShoppingCartServlet?method=add&num="+bookNum+"&bookId="+bookId);
}
//删除购物车行数据
function bookDelete(id) {
	initAjax();
	var url="../ShoppingCartServlet?method=remove";
	xmlhttp.open("post",url,true);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange = function() {
		//Ajax引擎状态为成功  
	    if (xmlhttp.readyState == 4) {
	        //HTTP协议状态为成功  
	        if (xmlhttp.status == 200) {
	        	var tr=document.getElementById("orderInfo_"+id);
		        tr.parentNode.removeChild(tr);
		        var table=document.getElementById("books");
		        if(table.rows.length==2){
			        table.parentNode.removeChild(table);
			        var message=document.createElement("div");
			        message.className="message";
			        message.innerHTML="购物车内暂时没有商品";
			        document.getElementById("content").appendChild(message);
		        }
	        }
	    }
	};
	xmlhttp.send("bookId="+id);
}
//清空购物车
function bookClean(){
	initAjax();
	var url="../ShoppingCartServlet?method=clear";
	xmlhttp.open("post",url,true);
	xmlhttp.onreadystatechange = function() {
		//Ajax引擎状态为成功  
	    if (xmlhttp.readyState == 4) {
	        //HTTP协议状态为成功  
	        if (xmlhttp.status == 200) {
	        	var table=document.getElementById("books");
		        table.parentNode.removeChild(table);
		        var message=document.createElement("div");
		        message.className="message";
		        message.innerHTML="购物车内暂时没有商品";
		        document.getElementById("content").appendChild(message);
	        }
	    }
	};
	xmlhttp.send(null);
}
//购物车选择图书
function checkPoint(checkNum) {
	var table=document.getElementById("books");
	var rl=table.rows.length;
	if(checkNum=="checkAll"){
		if(table.rows[0].cells[0].getElementsByTagName("input")[0].checked){
			for(var i=1;i<rl-1;i++){
				table.rows[i].cells[0].getElementsByTagName("input")[0].checked=true;
			}
		}else{
			for(var i=1;i<rl-1;i++){
				table.rows[i].cells[0].getElementsByTagName("input")[0].checked=false;
			}
		}
	}else{
		if(!this.checked){
			table.rows[0].cells[0].getElementsByTagName("input")[0].checked=false;
		}
		var all=true;
		for(var i=1;i<rl-1;i++){
			if(!table.rows[i].cells[0].getElementsByTagName("input")[0].checked){
				all=false;
			}
		}
		if(all){
			table.rows[0].cells[0].getElementsByTagName("input")[0].checked=true;
		}
	}
	var totalPrice=0.0;
	for(var i=1;i<rl-1;i++){
		if(table.rows[i].cells[0].getElementsByTagName("input")[0].checked){
			totalPrice+=parseFloat(table.rows[i].cells[4].innerHTML);
		}
	}
	table.rows[rl-1].cells[4].innerHTML="￥"+totalPrice.toFixed(1);
}
function myBookMouseOver() {
	var title=document.getElementById("shopTitle");
	var div=document.getElementById("list");
	title.style.background="#fff";
	title.style.borderBottom="none";
	div.style.display="block";
}
function myBookMouseOut() {
	var title=document.getElementById("shopTitle");
	var num=0;
	document.onmousemove = function(e) {
		num++;
		if(num==1){
			var x=e.clientX-title.getBoundingClientRect().left;
			var y=e.clientY-title.getBoundingClientRect().top;
			if((x>=0&&x<title.offsetWidth)&&(y>=title.offsetHeight)){
			}else{
				var div=document.getElementById("list");
				div.style.display="none";
				title.style.background="#fff";
				title.style.borderBottom="1px solid #bbb";
			}
		}
	};
}
function shoppingLisOut() {
	var div=document.getElementById("list");
	var num=0;
	document.onmousemove = function(e) {
		num++;
		if(num==1){
			var x=e.clientX-div.getBoundingClientRect().left;
			var y=e.clientY-div.getBoundingClientRect().top;
			if(x<0||x>div.offsetWidth||y>div.offsetHeight||y<0){
				div.style.display="none";
				var title=document.getElementById("shopTitle");
				title.style.background="#fff";
				title.style.borderBottom="1px solid #bbb";
			}
		}
	}

}
//购物车小提示窗体数据刷新
function showShoppingList(){
	initAjax();
	var url;
	if(document.title!="HOME"){
		url="../ShoppingCartServlet?method=show";
	}else{
		url="ShoppingCartServlet?method=show";
	}
	xmlhttp.open("post",url,true);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange =function(){
		//Ajax引擎状态为成功  
	    if (xmlhttp.readyState == 4) {
	        //HTTP协议状态为成功  
	        if (xmlhttp.status == 200) {
	        	var books=eval(xmlhttp.responseText);
	        	if(document.getElementById("nodata")){
        			var mess=document.getElementById("nodata");
	        		mess.parentNode.removeChild(mess);
        		}
	        	if(document.getElementById("myBookShopTable")){
	        		var t=document.getElementById("myBookShopTable");
		        	t.parentNode.removeChild(t);
	        	}
	        	if(books!=null&&books!=""){
	        		var div=document.getElementById("list");
	        		var table=document.createElement("table");
	        		table.setAttribute("id", "myBookShopTable");
	        		table.className="myBookShopTable";
	        		div.appendChild(table);
	        		//行数据
	        		for(var i=0;i<books.length;i++){
	        			var tr=document.createElement("tr");
	        			tr.setAttribute("id", "tr_"+books[i].item.id);
		        		table.appendChild(tr);
		        		//列数据
		        		var th_1=document.createElement("th");
		        		th_1.className="one";
		        		var img=document.createElement("img");
		        		if(document.title!="HOME"){
		        			img.setAttribute("src", "../style/img/book_logo/"+books[i].item.picPath);
		        		}else{
		        			img.setAttribute("src", "style/img/book_logo/"+books[i].item.picPath);
		        		}
		        		th_1.appendChild(img);
			        	tr.appendChild(th_1);
			        	
		        		var th_2=document.createElement("th");
		        		th_2.className="two";
		        		th_2.innerHTML=books[i].item.title;
			        	tr.appendChild(th_2);
			        	
			        	var th_3=document.createElement("th");
			        	th_3.className="three";
			        	var span=document.createElement("span");
			        	span.innerHTML=books[i].item.unprice;
			        	var text=document.createElement("text");
			        	text.innerHTML="x"+books[i].amount;
			        	th_3.appendChild(span);
			        	th_3.appendChild(text);
			        	tr.appendChild(th_3);
			        	
			        	var th_end=document.createElement("th");
			        	th_end.className="three";
			        	var a=document.createElement("a");
			        	a.setAttribute("href", "javascript:void(0)");
			        	a.setAttribute("onclick", "bookDeleteMin("+books[i].item.id+")")
			        	a.innerText="删除";
			        	th_end.appendChild(a);
			        	tr.appendChild(th_end);
	        		}
	        		var tr_end=document.createElement("tr");
	        		tr_end.setAttribute("id", "returnShopping");
	        		for(var i=0;i<3;i++){
	        			var tth=document.createElement("th");
	        			tr_end.appendChild(tth);
	        		}
	        		var a_goshopping=document.createElement("a");
	        		if(document.title!="HOME"){
	        			a_goshopping.setAttribute("href", "shoppingcart.jsp");
	        		}else{
	        			a_goshopping.setAttribute("href", "pages/shoppingcart.jsp")
	        		}
	        		a_goshopping.innerText="购物车结算";
	        		tr_end.appendChild(a_goshopping);
	        		table.appendChild(tr_end);
	        	}else{
	        		var div=document.getElementById("list");
	        		var nodata=document.createElement("div");
	        		nodata.setAttribute("id", "nodata");
	        		nodata.setAttribute("class", "nodata");
	        		nodata.innerHTML="购物车无商品";
	        		div.appendChild(nodata);
	        	}
	        }
	    }
	};
	xmlhttp.send(null);
}
//购物车小提示窗体删除行数据
function bookDeleteMin(id){
	initAjax();
	var url;
	var data="bookId="+id;
	if(document.title!="HOME"){
		url="../ShoppingCartServlet?method=remove";
	}else{
		url="ShoppingCartServlet?method=remove";
	}
	xmlhttp.open("post",url,true);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange =function(){
		//Ajax引擎状态为成功  
	    if (xmlhttp.readyState == 4) {
	        //HTTP协议状态为成功  
	        if (xmlhttp.status == 200) {
	        	var data=xmlhttp.responseText;
	        	if(data=="success"){
	        		var table=document.getElementById("myBookShopTable");
		    		var tr=document.getElementById("tr_"+id);
		    		tr.parentNode.removeChild(tr);
		    		if(table.rows.length==1){
		    			var t=document.getElementById("myBookShopTable");
			        	t.parentNode.removeChild(t);
			        	var div=document.getElementById("list");
		        		var nodata=document.createElement("div");
		        		nodata.setAttribute("id", "nodata");
		        		nodata.setAttribute("class", "nodata");
		        		nodata.innerHTML="购物车无商品";
		        		div.appendChild(nodata);
		    		}
	        	}
	        }
	    }
	};
	xmlhttp.send(data);
}
//获取url地址参数
function GetRequest() { 
	var url = location.search; //获取url中"?"符后的字串 
	var theRequest = new Object(); 
	if (url.indexOf("?") != -1) { 
		var str = url.substr(1); 
		strs = str.split("&"); 
		for(var i = 0; i < strs.length; i ++) { 
			theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]); 
		} 
	} 
	return theRequest; 
} 
/*========================分页js================================*/
function  creatPageBar() 
{
	var RJPageBar=document.getElementById('RJ-pagebar');
	var mark=document.getElementById('mark');
	var Request = GetRequest();
	var page;
	var pageCount=getCookie("pageTotal");
	var singleCount=10;
	if(Request["page"]){
		page=Request["page"];
	}else{
		page=1;
	}
	if(pageCount==0){
		pageCount=1;
	}
	if(pageCount<singleCount){
		singleCount=pageCount;
	}
	RJPageBar.innerHTML="";
	RJ_Pagebar({
		id:'RJ-pagebar', //容器ID : 必选参数
		CurrentPage:page,   //当前页 ： 可选参数，默认值为1
		SingleCount:singleCount,   //显示数目： 可选参数，只能为奇数，默认值为7，
		PageCount:pageCount,   //必选参数
		callback : function(pagenow,pagecount){
			mark.innerHTML='当前页:' + pagenow +',总共页:'+pagecount;
			}
		})
}
function RJ_Pagebar(opt){
	if(!opt.id){ return false};
	if(!opt.PageCount){return false};
	var _obj = document.getElementById(opt.id);
	var _cp = parseInt(opt.CurrentPage)>parseInt(opt.PageCount)?1:parseInt(opt.CurrentPage)||1;
	var _sc = parseInt(opt.SingleCount)>parseInt(opt.PageCount)?7:parseInt(opt.SingleCount)||7;
	var _pc = parseInt(opt.PageCount);
	if(_sc%2==0){_sc=_sc-1};
	var callback = opt.callback || function(){};
	
	if(_cp!=1)
	{
		var of=document.createElement('a');
		of.href="#"+(1);
		of.innerHTML="首页";
		_obj.appendChild(of);
		var oA=document.createElement('a');
		oA.href="#"+(_cp-1);
		oA.innerHTML="上一页";
		_obj.appendChild(oA);
	}
	else
	{
		var of=document.createElement('span');
		of.className="RU-pagedisabled";
		of.innerHTML="首页";
		_obj.appendChild(of);
		var oS=document.createElement('span');
		oS.className="RU-pagedisabled";
		oS.innerHTML="上一页";
		_obj.appendChild(oS);
	}
	
	if(_cp<=(_sc-1)/2)
	{
		for(i=1;i<=_sc;i++)
		{
			if(i==_cp)
			{
				var oS=document.createElement('span');
				oS.className='RU-pagenow';
				oS.innerHTML=i.toString().length==1?"0"+i:i;
				_obj.appendChild(oS);
			}
			else
			{
				var oA=document.createElement('a');
				oA.href="#"+i;
				oA.innerHTML=i.toString().length==1?"0"+i:i;
				_obj.appendChild(oA);
			}
		}
		var oS=document.createElement('span');
		oS.innerHTML="…";
		_obj.appendChild(oS);
	}
	else if(_cp<=_pc&&_cp>=_pc-(_sc-1)/2)
	{
		var oS=document.createElement('span');
		oS.innerHTML="…";
		_obj.appendChild(oS);
		for(i=_pc-_sc+1;i<=_pc;i++)
		{
			if(i==_cp)
			{
				var oS=document.createElement('span');
				oS.className='RU-pagenow';
				oS.innerHTML=i.toString().length==1?"0"+i:i;
				_obj.appendChild(oS);
			}
			else
			{
				var oA=document.createElement('a');
				oA.href="#"+i;
				oA.innerHTML=i.toString().length==1?"0"+i:i;
				_obj.appendChild(oA);
			}
		}
	}
	else
	{
		var oS=document.createElement('span');
		oS.innerHTML="…";
		_obj.appendChild(oS);
		
		for(i=_cp-(_sc-1)/2;i<(parseInt(_cp)+parseInt(_sc)-(_sc-1)/2);i++)
		{
			if(i==_cp)
			{
				var oS=document.createElement('span');
				oS.className='RU-pagenow';
				oS.innerHTML=i.toString().length==1?"0"+i:i;
				_obj.appendChild(oS);
			}
			else
			{
				var oA=document.createElement('a');
				oA.href="#"+i;
				oA.innerHTML=i.toString().length==1?"0"+i:i;
				_obj.appendChild(oA);
			}
		}
		var oS=document.createElement('span');
		oS.innerHTML="…";
		_obj.appendChild(oS);
	}
	
	if(_cp!=_pc)
	{
		var oA=document.createElement('a');
		oA.href="#"+(_cp+1);
		oA.innerHTML="下一页";
		_obj.appendChild(oA);
		var oe=document.createElement('a');
		oe.href="#"+(opt.PageCount);
		oe.innerHTML="末页";
		_obj.appendChild(oe);
	}
	else
	{
		var oS=document.createElement('span');
		oS.className="RU-pagedisabled";
		oS.innerHTML="下一页";
		_obj.appendChild(oS);
		var of=document.createElement('span');
		of.className="RU-pagedisabled";
		of.innerHTML="末页";
		_obj.appendChild(of);
	}
	
	callback(_cp,_pc);
	
	var cA=_obj.getElementsByTagName('a');
	for (var i=0;i<cA.length;i++)
	{
		cA[i].onclick=function(){
			var pagenum=parseInt(this.getAttribute('href').substring(1));
			_obj.innerHTML="";
//			RJ_Pagebar({
//				id:opt.id, //容器ID : 必选参数
//				CurrentPage:pagenum,   //当前页 ： 可选参数，默认值为1
//				SingleCount:opt.SingleCount,   //显示数目： 可选参数，只能为奇数，默认值为7，
//				PageCount:opt.PageCount,   //必选参数
//				callback:callback
//				})
			callBackObj="pageSearch";
			page=pagenum;
			if(getCookie("BookType")==0){
				doSearch("",getCookie("type"));
			}else{
				doSearch(getCookie("BookType"),getCookie("type"));
			}
				return false;
			}
	}
}
function getPublish() {
	document.getElementById("category").style.display="none";
	document.getElementById("publisher").style.display="block";
	document.getElementById("pointC").style.background="#fff";
	document.getElementById("pointC").style.color="#666";
	document.getElementById("pointP").style.background="#4a5e80";
	document.getElementById("pointP").style.color="#fff";
	setCookie("showType", "publish");
}
function getCategoties() {
	document.getElementById("publisher").style.display="none";
	document.getElementById("category").style.display="block";
	document.getElementById("pointC").style.background="#4a5e80";
	document.getElementById("pointC").style.color="#fff";
	document.getElementById("pointP").style.background="#fff";
	document.getElementById("pointP").style.color="#666";
	setCookie("showType", "category");
}
//=======================url特殊字符处理==========================
function urlDeal(url) {
	url=url.replace(/\#/g,"%23");
	url=url.replace(/\+/g,"%2B");
	url=url.replace(/\%/g,"%25");
	return url;
	
}//=======================cookie===============================
//写cookies 

function setCookie(name,value) 
{ 
    var Days = 30; 
    var exp = new Date(); 
    exp.setTime(exp.getTime() + Days*24*60*60*1000); 
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); 
} 

//读取cookies 
function getCookie(name) 
{ 
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
 
    if(arr=document.cookie.match(reg))
 
        return unescape(arr[2]); 
    else 
        return null; 
} 
//删除cookies 
function delCookie(name) 
{ 
    var exp = new Date(); 
    exp.setTime(exp.getTime() - 1); 
    var cval=getCookie(name); 
    if(cval!=null) 
        document.cookie= name + "="+cval+";expires="+exp.toGMTString(); 
}